package com.shunhao.network.api

import android.util.Log
import com.shunhao.network.newnet.NewApiException
import com.shunhao.network.newnet.ResponseResult
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.cancel
import kotlinx.coroutines.withContext

interface NewApi {

    // @GET("/api/banner/cloudExpoBanners")
    //suspend fun getRoomBannerTest(): ResponseResult<List<HomeBannerBean>>

}

suspend inline fun <T> apiCall(crossinline call: suspend CoroutineScope.() -> ResponseResult<T>): ResponseResult<T> {
    return withContext(Dispatchers.IO) {
        val res: ResponseResult<T>
        try {
            res = call()
        } catch (e: Throwable) {
            Log.e("ApiCaller", "request error", e)
            // 请求出错，将状态码和消息封装为 ResponseResult
            return@withContext NewApiException.build(e).toResponse<T>()
        }
        if (res.code == NewApiException.CODE_AUTH_INVALID) {
            Log.e("ApiCaller", "request auth invalid")
            // 登录过期，取消协程，跳转登录界面
            // 省略部分代码
            cancel()
        }
        return@withContext res
    }
}